package com.gettingstarted.gds.command
{
	import mx.rpc.IResponder;
	import com.adobe.cairngorm.commands.ICommand;
	import com.adobe.cairngorm.control.CairngormEvent;
	import mx.rpc.events.FaultEvent;
	import mx.rpc.IResponder;
	import mx.rpc.events.ResultEvent;
	import mx.utils.ObjectProxy;
	import com.gettingstarted.gds.model.ModelLocator;
	import com.adobe.cairngorm.business.ServiceLocator;
	import mx.rpc.AbstractService;
	import com.gettingstarted.gds.event.ContactEvent;
	import com.gettingstarted.gds.model.Contact;
	import mx.controls.Alert;
	import mx.rpc.AsyncToken;
	
	public class ContactCommand implements ICommand, IResponder
	{
		private var contactEvent:ContactEvent = null;
		private var _model: ModelLocator = ModelLocator.getInstance();
		private var service : AbstractService;
		
		
		public function ContactCommand()
		{
		}
		
		/**
		 * called by the controller(FrontController)
		 */ 
		public function execute(event:CairngormEvent):void{
			this.contactEvent = ContactEvent(event);
			this.service = ServiceLocator.getInstance().getService("contactService");
			var call : AsyncToken = service.saveContact(contactEvent._contact);
			//add responder to handle call back
			call.addResponder( this );
		}
		
		//called when service returns the value.
		public function result(event:Object) : void{
			var resultEvent:ResultEvent = event as ResultEvent;
			var _contact:Contact = Contact(resultEvent.result);
			//add the new model to the contact collections, which is then used by the view
			_model._contacts.addItem(_contact);
			
		}
		
		public function fault(event:Object) : void {
			var faultEvent : FaultEvent = FaultEvent( event );
			Alert.show( "Error Adding Contact!"+faultEvent.message );
			
		}


	}
}